#include "Engine.h"
#include "resource.h"

HWND Engine::OpenWindow(const char* cszWindowName, int nCmdShow)
{
	HWND tempHWnd;
	WNDCLASSEX wc;

	HINSTANCE hInstance = ::GetModuleHandle (NULL);
	assert (NULL != hInstance);
	HICON hIcon = NULL;
	hIcon = ::LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1));
	assert(NULL != hIcon);

	const char* cszWindowClassName = "MainWindow";

	wc.lpszClassName	= cszWindowClassName;
	wc.cbSize			= sizeof (WNDCLASSEX);
	wc.style			= CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc		= WindowProc;
	wc.hInstance		= m_hInstance;
	wc.hIcon			= hIcon;
	wc.hIconSm			= hIcon;
	wc.hCursor			= ::LoadCursor (NULL, IDC_ARROW);
	wc.hbrBackground	= (HBRUSH)::GetStockObject(BLACK_BRUSH);
	wc.lpszMenuName		= NULL;
	wc.cbClsExtra		= 0;
	wc.cbWndExtra		= 0;

	if (0 == RegisterClassEx(&wc))
		return 0;

	DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;

	tempHWnd = CreateWindow(cszWindowClassName,
		cszWindowName,
		dwStyle,
		0, 0, 
		g_scrWidth,g_scrHeight,
		NULL, NULL, m_hInstance, NULL);

	ShowWindow(tempHWnd, nCmdShow);//nCmdShow
	UpdateWindow (tempHWnd);
	return tempHWnd;
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch(uMsg)
	{
	case WM_DESTROY:
		{
			Engine::Ins()->toQuit = true;
			return 0;
		}
	case(WM_KEYDOWN):
		break;

	}
	return DefWindowProc (hWnd, uMsg, wParam, lParam);
}


Engine::Engine()
	: toQuit(false)
	, m_hWnd(NULL)
{}

void Engine::Init(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	// create a copy of Windows variables given at the program insertion
	m_hInstance = hInstance;
	m_hPrevInstance = hPrevInstance;
	m_lpCmdLine = lpCmdLine;
	m_nCmdShow = nCmdShow;
	m_hWnd = OpenWindow("MazeMan", nCmdShow);

	// initialize all the modules
	graphics.Init(m_hWnd);
	input.Init(m_hWnd, m_hInstance);
}

void Engine::Work()
{

	while(PeekMessage(&m_uMsg, NULL, 0, 0, PM_REMOVE))
	{
		TranslateMessage(&m_uMsg);
		DispatchMessage(&m_uMsg);
	}

	// input
	// update
	// draw
}

void Engine::Release()
{
	/* Call module release functions */
	graphics.Release();
	input.Release();
	PostQuitMessage(0);
}